package com.itheima.comfyui.ollama.client.config;

import com.itheima.comfyui.ollama.client.api.OllamaApi;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Configuration
public class OllamaConfig {


    @Bean
    public OllamaApi ollamaApi(ObjectMapper objectMapper) throws IOException {
              // 创建HTTP日志拦截器并设置日志级别为BODY，用于记录完整的请求和响应内容
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 构建OkHttpClient配置
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)           // 添加日志拦截器
                .retryOnConnectionFailure(true)               // 启用连接失败重试机制
                .connectTimeout(30, TimeUnit.SECONDS)         // 设置连接超时时间为30秒
                .build();

        // 构建Retrofit实例配置
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(String.format("http://192.168.100.129:11434"))  // 设置API基础URL
                .client(okHttpClient)                                     // 设置OkHttpClient实例
                .addConverterFactory(JacksonConverterFactory.create(objectMapper)) // 添加Jackson JSON转换器
                .build();

        // 创建OllamaApi接口的实现类实例
        OllamaApi ollamaApi = retrofit.create(OllamaApi.class);
        return ollamaApi;

    }

}
